import {Component, OnInit} from '@angular/core';
import {NzModalService, NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../../my-service/util.service";
import {TeamManagerService} from "../../../my-service/teamManager.service";
import {Router, ActivatedRoute} from "@angular/router";
import {Team} from "../../Team";
import {Packet} from "../../Packet";


@Component({
  selector: 'app-team-start',
  templateUrl: './team-start.component.html',
  styleUrls: ['./team-start.component.css'],
})
export class TeamStartComponent implements OnInit {
  //这个页面逻辑同起始页逻辑类似,优化可以把team这个对象放在服务中，当没有的时候再去取，
  readImgUrl = '';
  defaultImg = '';
  userGuid = null;
  teamGuid = null;
  teamName = null;
  navInfo = null;//传入面包屑的信息
  membersWidth = null;
  firstDuplicateArr = [];//2维数组
  lastDuplicateArr = [];//2维数组
  duplicateWidth = 195;//副本的宽度
  clientWidth = null;//当前窗口的宽度
  countDuplicateNum: number = 0;//总共能够容纳多少个副本
  modifyPacketIndex: number = 0;//修改副本时教案包的下标
  modfiyDuplicateIndex: number = 0;//修改副本时副本的下标
  modifyList: number = 0;//修改时修改的是第一列副本还是第二列副本
  team: any = {
    isEdit: null,
    packageArr: [],
    appArr: [],
    name: null,
    noAccreditMembers: [],
    haveAccreditMembers: [],
  };

  constructor(private nzModalService: NzModalService,
              private message: NzMessageService,
              private utilServe: UtilService,
              private teamServe: TeamManagerService,
              private router: Router,
              private routerInfo: ActivatedRoute) {
    this.readImgUrl = this.utilServe.readImgUrl;
    this.defaultImg = this.utilServe.defaultImg;
  }

  countMembersWidth(clientWidth) {
    this.membersWidth = (clientWidth * 0.8 - 40) * 0.75 - 10;
  }

  getUserGuid() {
    this.utilServe.getUserInfo().then(res => {
      if (res.status == 1) {
        this.userGuid = res.userGuid;
      }
    })
  };

  //获取团队
  getSingle(teamGuid) {
    this.teamServe.getSingleTeam(teamGuid).then(res => {
      if (res.status == 1) {
        let team = res.data[0];
        this.team = new Team(team.name, team.createTime, team.endTime, team.administrator, team.pk_teamGuid, team.status, team.adminGuid,team.limitNumber);
        this.isAdministrator(this.userGuid, this.team);
        this.getTeamMbers(true, this.team);
        this.getTeamMbers(false, this.team);
        this.getTeamApp(this.team);
        this.getAllPacket(this.team);
      }
    })
  }

  //获取团队成员详情
  getTeamUserInfo(team, type) {
    if (!type) {
      team.noAccreditMembers.forEach((member, index) => {
        this.teamServe.getUserInfo(member.FK_userGuid).then(res => {
          if (res.status == 1 && res.data) {
            team.noAccreditMembers[index] = res.data;
          } else if (res.status == 1 && !res.data) {
            team.noAccreditMembers.splice(index, 1);
            //  调用删除接口
          } else {
            console.log(res);
          }
        })
      });
    } else {
      team.haveAccreditMembers.forEach((member, index) => {
        this.teamServe.getUserInfo(member.FK_userGuid).then(res => {
          if (res.status == 1 && res.data) {
            team.haveAccreditMembers[index] = res.data;
            if (team.adminGuid == res.data.PK_UserGuid) {
              if (res.data.Cover) {
                team.Cover = res.data.Cover;
              }
            }
          } else if (res.status == 1 && !res.data) {
            team.haveAccreditMembers.splice(index, 1);
          } else {
            console.log(res);
          }
        })
      });
    }
  }

  //获取团队成员
  getTeamMbers(type, team) {
    this.teamServe.getTeamMembers(team.teamGuid, type).then(res => {
      if (res.status == 1) {
        if (type) {
          team.haveAccreditMembers = res.data;
          team.limitHeight(this.membersWidth); //计算每个团队是否需要限定高度
          this.getTeamUserInfo(team, true);
        } else {
          team.noAccreditMembers = res.data;
          this.getTeamUserInfo(team, false);
        }
      } else {
        console.log(res);
        this.message.error('获取团队成员失败');
      }
    })
  }

  //判断当前用户是否为团队管理团
  isAdministrator(userGuid, team) {
    this.teamServe.isAdministrator(team.teamGuid, userGuid).then(res => {
      if (res.status == 1) {
        team.isAdmin = res.isAdmin;
        //当管理员封面图片不存在时重新获取
        if(!team.Cover){
          this.teamServe.getUserInfo(team.adminGuid).then(res=>{
            if(res.status==1){
              team.Cover = res.data.Cover;
            }
          })
        }
      } else {
        console.log(res);
      }
    })
  }

  /*根据团队Guid获取团队应用*/
  getTeamApp(team) {
    this.teamServe.getAllApp(team.teamGuid).then(res => {
      if (res.code == 1 && res.data[0]) {
        team.appArr = res.data;
      } else {
        console.log(res);
      }
    })
  }

  /*根据团队Guid获取所有的教案包(包括副本)*/
  getAllPacket(team) {
    this.teamServe.getAllPacket(team.teamGuid).then(res => {
      if (res.code == 1 && res.data[0]) {
        res.data.forEach((packet, index) => {
          let packetArr = [];
          //实例化packet母本对象，并保存在数组中的0号元素
          packetArr[0] = new Packet(team.teamGuid, packet.PK_MyPacketGuid, packet.PacketName, packet.CoverUrl, packet.EnPacketName, packet.Description, packet.Publisher, packet.FK_AuthorGuid, packet.FK_CreatorGuid, packet.FK_OriginGuid);
          //有副本的情况
          if (packet.ChildrenPacket[0]) {
            packet.ChildrenPacket.forEach((childrenPacket, index) => {
              //实例化packet副本对象
              packetArr.push(new Packet(team.teamGuid, childrenPacket.PK_MyPacketGuid, childrenPacket.PacketName, childrenPacket.CoverUrl, childrenPacket.EnPacketName, childrenPacket.Description, childrenPacket.Publisher, childrenPacket.FK_AuthorGuid, childrenPacket.FK_CreatorGuid, childrenPacket.FK_OriginGuid));
            })
          }
          team.packageArr.push(packetArr);
          team.initDuplicate();
          this.countDuplicateNum = team.contTotalDuplicate(window.document.body.clientWidth, this.duplicateWidth);
          this.initShowDuplicate(team.duplicates);
        });
      } else {
        console.log(res);
      }
    })
  }

  //初始化显示副本2排显示
  initShowDuplicate(duplicates) {
    duplicates.forEach((duplicateArr, index) => {
      if (duplicateArr.length >= 1) {
        //奇数的位置的副本放在第一列，偶数的放在第二列
        this.firstDuplicateArr[index] = [];
        this.lastDuplicateArr[index] = [];
        duplicateArr.forEach((duplicate, duplicateIndex) => {
          if (duplicateIndex < this.countDuplicateNum) {
            if ((duplicateIndex + 1) % 2 == 0) {
              this.lastDuplicateArr[index].push(duplicate);
            } else {
              this.firstDuplicateArr[index].push(duplicate);
            }
          }
        })
      }
    });
  }

  ngOnInit() {
    this.teamGuid = this.routerInfo.snapshot.params.id;
    this.teamName = this.routerInfo.snapshot.params.name;
    this.navInfo = {
      teamName: this.teamName
    };
    this.countMembersWidth(window.document.body.clientWidth);
    this.getUserGuid();
    this.getSingle(this.teamGuid);
    let that = this;
    window.onresize = function () {
      that.countMembersWidth(window.document.body.clientWidth);
      that.countDuplicateNum = that.team.contTotalDuplicate(window.document.body.clientWidth, that.duplicateWidth);
      that.initShowDuplicate(that.team.duplicates);
      that.team.initShowMoreDuplicate(that.countDuplicateNum);
    }
  }

  //修改团队名称
  modifyTeamName(team) {
    let data = {
      name: team.name,
      PK_teamGuid: team.teamGuid
    };
    this.teamServe.modifyTeamName(data).then(res => {
      if (res.status == 1) {
        this.message.success('修改团队名成功');
        team.isModifyTeamName = !team.isModifyTeamName;
      }
    })
  };

  //打开团队管理设置
  openAdminSetting(team) {
    team.openAdminSeeting = true;
  }

  //关闭团队设置
  closeAdminSetting(event) {
    this.team = event;
  }

  /*移除用户授权*/
  removeAccredit(team, index) {
    this.utilServe.comfirm('您确定要删除该用户的授权么？', () => {
      let data = {
        FK_teamGuid: team.teamGuid,
        FK_userGuid: team.haveAccreditMembers[index].PK_UserGuid
      };
      this.teamServe.removeAccredit(data).then(res => {
        if (res.status == 1 && res.msg == '移除授权成功') {
          this.message.success('删除用户授权成功');
          let member =team.haveAccreditMembers.splice(index, 1);
          team.noAccreditMembers.push(member[0]);
        } else {
          console.log(res);
        }
      })
    })
  }
  //移除团队成员
  removeMembers(team,index){
    if(team.adminGuid == team.haveAccreditMembers[index].PK_UserGuid ){
      this.message.error('当前用户为团队管理员不能将其移除团队，请更换团队管理员后将其移除');
      return;
    }
    this.utilServe.comfirm('您确定要将该用户移出团队么？', () => {
      let data = {
        FK_teamGuid: team.teamGuid,
        FK_userGuid: team.haveAccreditMembers[index].PK_UserGuid
      };
      this.teamServe.removeMembers(data).then(res => {
        if (res.status == 1 && res.msg == '移除团队成员成功') {
          this.message.success(res.msg);
          let member = team.haveAccreditMembers.splice(index, 1);
        } else {
          console.log(res);
        }
      })
    })
  }

//打开用户授权
  openAddAccredit(team) {
    team.openAccredit = true;
  }

  //关闭用户授权
  onCloseAddAccredit(event, team) {
    team = event;
  }

  //去到更多副本页面
  moreDuplicate(packetName, packetGuid) {
    this.router.navigate(['../package', {
      id: this.teamGuid,
      name: this.teamName,
      p_id: packetGuid,
      p_name: packetName
    }], {relativeTo: this.routerInfo});
  }

  //去到每个应用
  goApp(appUrl, appName) {
    this.utilServe.comfirm(`您确认离开当前页面去到${appName}应用吗?`, () => {
      window.open(appUrl);
    })
  }

  //创建教案包副本
  createDuplicate(teamGuid, packetGuid, packetName, index) {
    this.utilServe.comfirm(`您确认创建${packetName}教案包副本吗？`, () => {
      this.teamServe.createDuplicate(teamGuid, packetGuid).then(res => {
        if (res.code == 1) {
          let packet = res.data;
          this.team.duplicates[index].push(new Packet(this.team.teamGuid, packet.PK_MyPacketGuid, packet.PacketName, packet.CoverUrl, packet.EnPacketName, packet.Description, packet.Publisher, packet.FK_AuthorGuid, packet.FK_CreatorGuid, packet.FK_OriginGuid));
          this.initShowDuplicate(this.team.duplicates);
          this.team.initShowMoreDuplicate(this.countDuplicateNum);
          this.message.success(`您成功创建${packetName}教案包副本`);
        } else if (res.code == 0) {
          this.message.error(`创建${packetName}教案包副本失败，请稍后再试`);
          console.log(res);
        }
      })
    })
  }

  //删除教案包副本
  deleteDuplicate(duplicateGuid, duplicateName, packIndex, index) {
    this.utilServe.comfirm(`您确认删除${duplicateName}吗？`, () => {
      this.teamServe.deleteDuplicate(duplicateGuid).then(res => {
        if (res.code == 1) {
          this.team.deleteDuplicate(packIndex, duplicateGuid);
          this.initShowDuplicate(this.team.duplicates);
          this.team.initShowMoreDuplicate(this.countDuplicateNum);
          this.message.success(`您成功删除${duplicateName}`);
        }
      })
    })
  }

  //打开修改教案包副本
  modifyDuplicate(duplicate, packetIndex, duplicateIndex, list) {
    duplicate.isModify = true;
    this.modifyPacketIndex = packetIndex;
    this.modfiyDuplicateIndex = duplicateIndex;
    this.modifyList = list;
  }

  //关闭教案包修改
  closeModifyDuplicate(event) {
    if (this.modifyList == 1) {
      this.firstDuplicateArr[this.modifyPacketIndex][this.modfiyDuplicateIndex] = event;
    } else {
      this.lastDuplicateArr[this.modifyPacketIndex][this.modfiyDuplicateIndex] = event;
    }
  }

  //去教案包应用
  goPacket(packetGuid, packetName, flag) {
    if (flag) {
      return;
    } else {
      this.message.warning(`请您从超级教案中的团队教案包进入${packetName}`);
    }
  }
}
